<?php

namespace app\store\model\store;

use app\common\model\store\Shop as ShopModel;
use Lvht\GeoHash;
use app\store\model\store\User as StoreUserModel;
use think\Db;

/**
 * 商家门店模型
 * Class Shop
 * @package app\store\model\store
 */
class Shop extends ShopModel
{
    /**
     * 获取列表数据
     * @param array $param
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($param = [])
    {
        // 查询列表数据
        return $this->setListQueryWhere($param)->with(['storeuser'])
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);
    }

    /**
     * 获取所有门店列表
     * @param array $param
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getAllList($param = [])
    {
        return (new static)->setListQueryWhere($param)->select();
    }

    /**
     * 设置列表查询条件
     * @param array $param
     * @return $this
     */
    private function setListQueryWhere($param = [])
    {
        // 查询参数
        $param = array_merge(['is_check' => '', 'search' => '', 'status' => null,], $param);
        is_numeric($param['is_check']) && $param['is_check'] > -1 && $this->where('is_check', '=', (int)$param['is_check']);
        !empty($param['search']) && $this->where('shop_name|linkman|phone', 'like', "%{$param['search']}%");
        is_numeric($param['status']) && $this->where('status', '=', (int)$param['status']);
        isset($param['shop_id']) && $param['shop_id'] > 0 && $this->where('shop_id', '=', (int)$param['shop_id']);
        return $this->where('is_delete', '=', '0')->order(['sort' => 'asc', 'create_time' => 'desc']);
    }

    /**
     * 新增记录
     * @param $data
     * @return bool
     * @throws \Exception
     */
    public function add($data)
    {
        if (!$this->validateForm($data)) {
            return false;
        }
        $this->startTrans();
        try {
//            $data['create_time'] = time();
//            $data['update_time'] = time();
            $user_name = $data['user_name'];
            $password = $data['password'];
//            unset($data['user_name']);
//            unset($data['password']);
//            $shop_id = $this->allowField(true)->insertGetId($this->createData($data));
            $shop_id = $this->allowField(true)->save($this->createData($data));
            //插入管理员
            $user_add['user_name'] = $user_name;
            $user_add['real_name'] = $user_name;
            $user_add['password'] = yoshop_hash($password);
            $user_add['is_super'] = 0;
            $user_add['user_type'] = 2;
//            $user_add['shop_user_id'] = $shop_id;
            $user_add['shop_user_id'] = $this['shop_id'];
            $user_add['wxapp_id'] = self::$wxapp_id;
            $user_add['create_time'] = time();
            $user_add['update_time'] = time();
            $store_user_id = Db::name('store_user')->insertGetId($user_add);
            //权限表
            $role_add['store_user_id'] = $store_user_id;
            $role_add['role_id'] = 10001;//门店
            $role_add['wxapp_id'] = self::$wxapp_id;
            $role_add['create_time'] = time();
//            $role_add['update_time'] = time();
            Db::name('store_user_role')->insert($role_add);
            $this->commit();
            return  true;
        }catch (\Exception $exception){
            $this->rollback();
            $this->error = $exception->getMessage();
            return false;
        }
        return $this->allowField(true)->save($this->createData($data));
    }

    /**
     * 编辑记录
     * @param $data
     * @return false|int
     */
    public function edit($data)
    {
        if (!$this->validateForm($data,'edit')) {
            return false;
        }
        return $this->allowField(true)->save($this->createData($data)) !== false;
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }

    /**
     * 创建数据
     * @param array $data
     * @return array
     */
    private function createData($data)
    {
        $data['wxapp_id'] = self::$wxapp_id;
        // 格式化坐标信息
        $coordinate = explode(',', $data['coordinate']);
        $data['latitude'] = $coordinate[0];
        $data['longitude'] = $coordinate[1];
        // 生成geohash
        $Geohash = new Geohash;
        $data['geohash'] = $Geohash->encode($data['longitude'], $data['latitude']);
        return $data;
    }

    /**
     * 表单验证
     * @param $data
     * @param $type
     * @return bool
     */
    private function validateForm($data,$type="add")
    {
        if (!isset($data['logo_image_id']) || empty($data['logo_image_id'])) {
            $this->error = '请选择门店logo';
            return false;
        }
        if ($type == 'add'){
            if ($data['user_name'] == '' || $data['password'] == ''){
                $this->error = '请输入门店账号或密码';
                return false;
            }
            $store_user = \app\common\model\store\User::detail(['user_name'=>$data['user_name'],'user_type'=>2]);
            if ($store_user){
                $this->error = '门店账号已存在';
                return false;
            }
        }

        return true;
    }

}